import numpy

import rpy2.robjects as robjects
import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr
from django.conf import settings
import os
from mainapp.helpers import replace_dataset_symbol, get_new_filepathimage


r = robjects.r
dev_off = r('dev.off')
cluster = importr("cluster")


def execute(parameters):

    file = parameters['file']
    attrs = parameters['attrs']
    options = parameters['options']
    
    data = numpy.genfromtxt(parameters['file'], usecols=parameters['data_columns'], delimiter=parameters['delimiter'])
    replace_dataset_symbol(attrs, data)
    
    kmeans_data = r.kmeans(*attrs, **options)
    clusplot_data = kmeans_data[0]
    
    image_path = get_new_filepathimage()
    
    r.png(image_path)
    cluster.clusplot(data, clusplot_data, which_plot=[3,4], main='Test')
    dev_off()
    
    return {'image_path':image_path, 'description':str(kmeans_data)}

